package com.free4inno.knowledgems.controller;

import com.free4inno.knowledgems.utils.PdfUtils;
import com.itextpdf.text.DocumentException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * @author : liuxinyuan
 * @date : 23:10 2021/11/20
 */

@Slf4j
@Controller
public class PdfController {

    @Autowired
    private PdfUtils pdfUtils;

    @RequestMapping("/topdf")
    public ResponseEntity<FileSystemResource> topdf(@RequestParam(value = "id", required = true) int id,
                                                    @RequestParam(value = "isBook", required = false) boolean isBook,
                                                    HttpSession session, HttpServletRequest request, HttpServletResponse httpServletResponse, Map param) throws Exception {
        String pdfTempPath = pdfUtils.toPdf(id);
        return export(new File(pdfTempPath +id+".pdf"),id);
    }
    public ResponseEntity<FileSystemResource> export(File file,int id) throws UnsupportedEncodingException {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment;filename*=UTF-8''"+URLEncoder.encode(pdfUtils.get_title(),"UTF-8")+".pdf");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity .ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new FileSystemResource(file));
    }
}
